package treeview.container;

import document.Context;
import treemodel.Unit;
import search.Visitor;
import treeview.NodeView;

import java.awt.*;
import java.util.ArrayList;

/**
 * Created by Pavel Nikolaev
 */
public class WrappedHorizontalContainer extends VerticalContainer {
    protected NodeView[] myUnitViews;

    public WrappedHorizontalContainer(ArrayList<Unit> units, Context context) {
        this.myUnitViews = new NodeView[units.size()];
        int index = 0;
        for (Unit unit :units) myUnitViews[index++] = unit.createView(context);
    }

    private void wrap(int widthToFitInto) {
        myNodeViews.clear();
        HorizontalContainer line = createFirstSubLine();
        myNodeViews.add(line);
        int awaitedWidth = 0;
        for (NodeView view : myUnitViews) {
            awaitedWidth += view.getWidth();
            if (awaitedWidth <= widthToFitInto) {
                line.add(view);
            } else {
                line = createSubLine();
                myNodeViews.add(line);
                line.add(view);
                awaitedWidth = view.getWidth();
            }
        }
    }

    @Override
    public void fitIntoWidth(Graphics g, int widthToFitInto) {
        for (NodeView myUnitView : myUnitViews) myUnitView.fitIntoWidth(g, widthToFitInto);
        wrap(widthToFitInto);
        super.fitIntoWidth(g, widthToFitInto);
    }

    protected HorizontalContainer createFirstSubLine() {
        return new HorizontalContainer();
    }

    protected HorizontalContainer createSubLine() {
        return new HorizontalContainer();
    }

    @Override
    public void accept(Visitor visitor) {
         for (NodeView unit :myUnitViews) unit.accept(visitor);
    }
}
